// Element UI 的版本
const ELEMENT_UI_VERSION = '2.15.14';

// 默认主题颜色
const DEFAULT_THEME = '#409EFF';

class ThemeChanger{
	constructor(){
		this.chalk = '';
	}

    /**
     * 切换主题颜色
     * @param {string} newColor - 新的主题颜色
     */
	async changeThemeColor(newColor){
		if(typeof newColor !== 'string') return;

		const themeCluster = this.getThemeCluster(newColor.replace('#', ''));
		const getHandler = (id) => {
			return () => {
				const originalCluster = this.getThemeCluster(DEFAULT_THEME.replace('#', ''));
				const newStyle = this.updateStyle(this.chalk, originalCluster, themeCluster);

				let styleTag = document.getElementById(id);
				if(!styleTag){
					styleTag = document.createElement('style');
					styleTag.setAttribute('id', id);
					document.head.appendChild(styleTag);
				}
				styleTag.innerText = newStyle;
			};
		};

		if(!this.chalk){
			const url = `https://unpkg.com/element-ui@${ELEMENT_UI_VERSION}/lib/theme-chalk/index.css`;
			await this.loadCSSString(url);
		}

		const chalkHandler = getHandler('chalk-style');
		chalkHandler();
	}

    /**
     * 获取主题色阶
     * @param {string} theme - 主题颜色
     * @returns {string[]} - 色阶数组
     */
	getThemeCluster(theme){
		const tintColor = (color, tint) => {
			let red = parseInt(color.slice(0, 2), 16);
			let green = parseInt(color.slice(2, 4), 16);
			let blue = parseInt(color.slice(4, 6), 16);

			if(tint === 0) return [red, green, blue].join(',');

			red += Math.round(tint * (255 - red));
			green += Math.round(tint * (255 - green));
			blue += Math.round(tint * (255 - blue));

			return `#${red.toString(16)}${green.toString(16)}${blue.toString(16)}`;
		};

		const shadeColor = (color, shade) => {
			let red = parseInt(color.slice(0, 2), 16);
			let green = parseInt(color.slice(2, 4), 16);
			let blue = parseInt(color.slice(4, 6), 16);

			red = Math.round((1 - shade) * red);
			green = Math.round((1 - shade) * green);
			blue = Math.round((1 - shade) * blue);

			return `#${red.toString(16)}${green.toString(16)}${blue.toString(16)}`;
		};

		const clusters = [theme];
		for(let i = 0; i <= 9; i++){
			clusters.push(tintColor(theme, Number((i / 10).toFixed(2))));
		}
		clusters.push(shadeColor(theme, 0.1));
		return clusters;
	}

    /**
     * 加载 CSS 文件
     * @param {string} url - CSS 文件的 URL
     */
	loadCSSString(url){
		return new Promise((resolve) => {
			const xhr = new XMLHttpRequest();
			xhr.onreadystatechange = () => {
				if(xhr.readyState === 4 && xhr.status === 200){
					this.chalk = xhr.responseText.replace(/@font-face{[^}]+}/, '');
					resolve();
				}
			};
			xhr.open('GET', url);
			xhr.send();
		});
	}

    /**
     * 更新样式
     * @param {string} style - 原始样式
     * @param {string[]} oldCluster - 默认主题色阶
     * @param {string[]} newCluster - 新主题色阶
     * @returns {string} - 更新后的样式
     */
	updateStyle(style, oldCluster, newCluster){
		let newStyle = style;
		oldCluster.forEach((color, index) => {
			newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index]);
		});
		return newStyle;
	}
}

// 创建 ThemeChanger 实例
const themeChanger = new ThemeChanger();
export default themeChanger;